<?php
// +----------------------------------------------------------------------
// |  [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-present http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\meeting\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use TCPDF;

class OrderController extends AdminBaseController
{

    /*
     * 展位
     * 押金、审图费、特装管理费
     * @param
     * $return
     */
    public function fee()
    {
        $builder = Db::table('ims_hc_meet_builder')
            ->where('builder_id', session('BUILDER_ID'))
            ->find();
        $where   = [];
        $where[] = ['order_no', 'like', '%' . input('keyword', '') . '%'];
        $where[] = ['uid', '=', $builder['uid']];
        $data    = Db::table('ims_hc_meet_fee')
            ->field('a.*,b.title meeting_title')
            ->alias('a')
            ->join('we77.ims_hc_meet b', 'a.meeting_id=b.id')
            ->where($where)
            ->order('create_time desc')
            ->paginate(10);
        $page    = $data->render();
        $list    = $data->toArray();

        $this->assign('list', $list['data']);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /*
     * 详情
     * detail
     * @param
     * $return
     */
    public function detail($id)
    {
        $where[]        = ['a.id', '=', $id];
        $info           = Db::table('ims_hc_meet_fee')
            ->field('a.*,b.title meeting_title')
            ->alias('a')
            ->join('we77.ims_hc_meet b', 'a.meeting_id=b.id')
            ->where($where)
            ->find();
        $info['remark'] = empty($info['remark']) ? [] : json_decode($info['remark'], 1);
        $info['image']  = empty($info['image']) ? [] : json_decode($info['image'], 1);

        // 报图信息
        $is_sure = $this->checkPicture($info['room_id'],$info['builder_id']);
        $info['is_sure'] = $is_sure['code'];

        $this->assign('info', $info);
        return $this->fetch();
    }


    /*
     * 保存缴费证明
     * saveOrder
     * @param
     * $return
     */
    public function saveOrder()
    {
        $id             = input('id');

        // 报图没确认之前，不能缴费
        $info =  Db::table('ims_hc_meet_fee')->find($id);

        if(!$info['type']){
            $is_sure = $this->checkPicture($info['room_id'], $info['builder_id']);
            if($is_sure['code']!=1) $this->error('报图没确认，不能缴费');
        }


        $data['image']  = input('image');
        $data['image']  = empty($data['image']) ? '' : json_encode($data['image'], 1);
        $data['is_pay'] = 1;
        $re             = Db::table('ims_hc_meet_fee')
            ->where(['id' => $id])
            ->update($data);
        if ($re) {
            $this->success('成功');
        } else {
            $this->error('失败');
        }
    }


    /*
     * 生成订单
     * */
    public function order($room_id)
    {
        $room    = Db::table('ims_hc_meet_room')
            ->where(['room_id' => $room_id, 'builder_id' => session('BUILDER_ID')])
            ->find();
        $builder = Db::table('ims_hc_meet_builder')
            ->where(['builder_id' => session('BUILDER_ID')])
            ->find();
        if (empty($room)) {
            $this->error('用户信息错误');
        }
        $data = [];
        //  判断是否  推荐 搭建商

        // 根据面积计算费用 服务
        if ($room['area'] <= 50) {
            $shentu  = 200;
            $shigong = 10000;
        } elseif ($room['area'] < 100) {
            $shentu  = 200;
            $shigong = 20000;
        } elseif ($room['area'] <= 200) {
            $shentu  = 300;
            $shigong = 30000;
        } else {
            $shentu  = 500;
            $shigong = 50000;
        }

        if ($builder['is_recommend']) {
            $builderInfo = 20;
            // 是 》
            // 施工押金 是否已交
            $info = Db::table('ims_hc_meet_fee')
                ->where(['uid' => $builder['uid'], 'type' => 1])
                ->find();
            if (empty($info)) {
                // 否 》生成施工押金订单
                $data = [
                    'uid'          => $builder['uid'],
                    'title'        => '施工押金',
                    'total'        => 80000,
                    'area'         => $room['area'],
                    'number'       => $room['number'],
                    'bank_name'    => $room['bank_name'],
                    'company'      => $room['company'],
                    'bank_no'      => $room['bank_no'],
                    'order_no'     => $this->getOrderSn(),
                    'builder_id'   => $builder['builder_id'],
                    'meeting_id'   => session('MEETING_ID'),
                    'builder_name' => $builder['builder_name'],
                    'create_time'  => time(),
                    'type'         => 1,
                ];
                Db::table('ims_hc_meet_fee')->insert($data);

            }
            //审图费 特装管理费是否交
            $info2 = Db::table('ims_hc_meet_fee')
                ->where(['type' => 0, 'room_id' => $room_id])
                ->find();
            if (empty($info2)) {
                // 否 》生成审图费 特装管理费
                $data1 = [
                    [
                        'name' => '审图费',
                        'val'  => $shentu,
                    ], [
                        'name' => '特装管理费',
                        'val'  => $builderInfo * $room['area'],
                    ],
                ];
                $data2 = [
                    'uid'          => $builder['uid'],
                    'title'        => '审图费、特装管理费',
                    'total'        => bcadd($shentu, bcmul($builderInfo, $room['area'], 2), 2),
                    'order_no'     => $this->getOrderSn(),
                    'area'         => $room['area'],
                    'number'       => $room['number'],
                    'bank_name'    => $room['bank_name'],
                    'company'      => $room['company'],
                    'bank_no'      => $room['bank_no'],
                    'builder_id'   => $builder['builder_id'],
                    'meeting_id'   => $builder['meeting_id'],
                    'builder_name' => $builder['builder_name'],
                    'create_time'  => time(),
                    'remark'       => json_encode($data1),
                    'room_id'      => $room_id,
                ];
                Db::table('ims_hc_meet_fee')->insert($data2);
            } else {
                $info2['remark'] = json_decode($info2['remark'], 1);
                $this->success('您已关联此展位');exit;
            }

        } else {
            $builderInfo = 40;
            // 否 》 生成施工押金  审图费  特装管理费
            //审图费 特装管理费是否交
            $info2 = Db::table('ims_hc_meet_fee')
                ->where(['type' => 0, 'room_id' => $room_id])
                ->find();

            if (empty($info2)) {
                // 否 》生成审图费 特装管理费
                $data1 = [
                    [
                        'name' => '施工押金',
                        'val'  => $shigong,
                    ],
                    [
                        'name' => '审图费',
                        'val'  => $shentu,
                    ], [
                        'name' => '特装管理费',
                        'val'  => $builderInfo * $room['area'],
                    ],
                ];
                $data2 = [
                    'uid'          => $builder['uid'],
                    'title'        => '施工押金、审图费、特装管理费',
                    'total'        => bcadd($shentu + $shigong, bcmul($builderInfo, $room['area'], 2), 2),
                    'order_no'     => $this->getOrderSn(),
                    'area'         => $room['area'],
                    'number'       => $room['number'],
                    'bank_name'    => $room['bank_name'],
                    'company'      => $room['company'],
                    'bank_no'      => $room['bank_no'],
                    'meeting_id'   => $builder['meeting_id'],
                    'builder_id'   => $builder['builder_id'],
                    'builder_name' => $builder['builder_name'],
                    'create_time'  => time(),
                    'remark'       => json_encode($data1),
                    'room_id'      => $room_id,
                ];
                Db::table('ims_hc_meet_fee')->insert($data2);
            } else {
                $info2['remark'] = json_decode($info2['remark'], 1);
                $this->success('您已关联此展位');exit;
            }
        }
    }

    /*
    * getOrderSn
    * @param
    * $return
    */
    public function getOrderSn($len = 5)
    {
        $number = date('YmdHis') . random($len, 1);
        return $number;
    }

    /*
     * 检测是否报图确认
     * checkOrder
     * @param
     * $return
     */
    public function checkPicture($room_id=0,$builder_id=0)
    {
        if(empty($room_id)||empty($builder_id)) return ['code'=>0,'msg'=>'参数错误'];
        $info = Db::table('ims_hc_meet_room_check_picture')
            ->where(['room_id'=>$room_id, 'builder_id'=>$builder_id])
            ->find();
        // 订单是否是施工押金
        if($info&&$info['status']==1){

            return ['code'=>1];

        }else{
            return ['code'=>0,'msg'=>'报图没确认，不能缴费'];
        }
    }

    /*
     * 展位-付款通知单
     * showPayOrder
     * @param
     * $return
     */
    public function showPayOrder()
    {
        $room_id = input('room_id');
        $builder = Db::table('ims_hc_meet_builder')
            ->where('builder_id', session('BUILDER_ID'))
            ->find();
        $pdf = new \TCPDF('A4-L');
        $pdf->AddPage();
        $pdf->setPrintHeader(false);    //页面头部横线取消
        $pdf->setPrintFooter(false); //页面底部更显取消

        $PDF_MARGIN_LEFT = 25;
        $PDF_MARGIN_TOP = 30;//留给页眉的空间
        $PDF_MARGIN_RIGHT = 25;
        $pdf->SetMargins($PDF_MARGIN_LEFT, $PDF_MARGIN_TOP, $PDF_MARGIN_RIGHT);

        $file = "./upload/00.png";
        $x='';
        $y='';
        $w=190;
        $h=30;
        $type='';
        $link='';
        $align='';
        $resize=false;
        $dpi=300;
        $palign='';
        $ismask=false;
        $imgmask=false;
        $border=0;
        $fitbox=false;
        $hidden=false;
        $fitonpage=false;
        $alt=false;
        $altimgs=array();


        $pdf->Image($file, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border, $fitbox, $hidden, $fitonpage, $alt, $altimgs);
        // 施工押金、特装管理费，审图费
        $h = '';
        $total=0;
        if($builder['is_recommend']){
            // 推荐搭建商
            $shi = Db::table('ims_hc_meet_fee')
                ->where(['builder_id'=>session('BUILDER_ID'),'meeting_id'=>session('MEETING_ID')])
                ->find();
                $h.='<tr><td>1</td><td>'.$shi['title'].'</td><td>1</td><td>'.$shi['total'].'</td><td>'
                    .$shi['total'].'</td></tr>';
            $total += $shi['total'];
        }
        $where=['room_id'=>$room_id,'builder_id'=>session('BUILDER_ID'),'meeting_id'=>session('MEETING_ID')];
        $info = Db::table('ims_hc_meet_fee')
            ->where($where)
            ->find();
        if($info&&!empty($info['remark'])){
            $remark = json_decode($info['remark'],1);
            foreach ($remark as $k=>$v){
                $h.='<tr><td>'.($k+2).'</td><td>'.$v['name'].'</td><td>1</td><td>'.$v['val'].'</td><td>'
                    .$v['val'].'</td></tr>';
                $total += $v['val'];
            }
        }

        $roomInfo = Db::table('ims_hc_meet_room')
            ->where(['room_id'=>$room_id])
            ->find();
        $number = $roomInfo["number"];
        $exhibitor_name = $roomInfo["exhibitor_name"];
        $builder_name = $roomInfo["builder_name"];

        $html = <<<EOD
        <h2 style="text-align: center">主场服务-付款通知单</h2>
<table border="1" style="text-align: center ">
<tr><td colspan="5" style="text-align: left">展位号以及展位名称：$number $exhibitor_name</td></tr>
<tr><td colspan="5" style="text-align: left">展位搭建商：$builder_name</td></tr>
<tr><th>序号</th><th>项目</th><th>数量</th><th>单价</th><th>总价</th></tr>
$h
<tr><td colspan="4">合计：</td><td>$total</td></tr>

</table>
<p style="font-size: 10px">注:1.请各企业收到“主场服务汇款通知单”后，于3个工作日内按照付款通知单中款项汇至指定账户，并提交企业开票信息(增值税普通发票(电子普票附上邮箱))2.订单在全部付款收到后生效，汇款方承担全部汇款手续费。只接受公对公付款，请勿以私人名称汇款，主场服务商在发票中开具的单位名称将与汇款单位一致。3.各企业汇款后，将“汇款凭证”以及“发票信息(制成电子版)标明展位号”回传至主场服务商邮箱sdjzjnz@126.com，如未按照规定时间内付款以及回传“发票信息(制成电子版)”，将视为“现场申报”，相应项加收“现场服务费”。4.如因企业个人原因(未及时提供开票信息或信息有误等)，导致发票漏开/错开等，由各企业自行负责。</p>
<p style="font-size: 12px;">主场预申报负责人:刘伟 联系方式:18678948991</p>
<p style="font-size: 12px;">汇款信息:</p>
<p style="font-size: 12px;">单位名称: 山东泓橙信息技术有限公司</p>
<p style="font-size: 12px;">帐号: 536903489510701</p>
<p style="font-size: 12px;">开户行: 招商银行股份有限公司潍坊高新支行</p>
EOD;

        $pdf->SetFont('cid0cs', '', 14);
        $pdf->writeHTMLCell(0, 0, '', '50', $html, 0, 1, 0, true, '', true);

        $pdf->Output(date('YmdHis').'.pdf', 'D');
    }
    /*
         * 展位-电费详单
         * showPayOrder
         * @param
         * $return
         */
    public function showPayOrder2()
    {
        $room_id = input('room_id');
        $builder = Db::table('ims_hc_meet_builder')
            ->where('builder_id', session('BUILDER_ID'))
            ->find();
        $where=[
            'b.class_id'=>12, // 水电
            'a.uid'=>$builder['uid'],
            'a.meeting_id'=>session('MEETING_ID')
        ];
        $info = Db::table('ims_hc_meet_order')
            ->alias('a')
            ->field('a.*,b.hire_id,b.hire_name,b.class_id,b.class_name,b.price,b.deposit,b.number')
            ->leftJoin('we77.ims_hc_meet_order_goods b','a.order_no=b.order_no')
            ->where($where)
            ->select();
        $data=[];
        if($info) {
            $data = $info->toArray();
        }else{
            $this->error('暂无水电订单');
        }
        // 水电
        $html1 = '';
        $total=0;
        if($data&&!empty($data)){
            foreach ($data as $k=>$v){
                $html1.='<tr><td>'.($k+2).'</td><td>'.$v['hire_name'].'</td><td>'.$v['number'].'</td><td>'
                    .$v['price'].'</td><td>'
                    .($v['price']*$v['number']).'</td></tr>';
                $total += $v['price']*$v['number'];
            }
        }

        $pdf = new \TCPDF('A4-L');
        $pdf->AddPage();
        $pdf->setPrintHeader(false);    //页面头部横线取消
        $pdf->setPrintFooter(false); //页面底部更显取消

        $PDF_MARGIN_LEFT = 25;
        $PDF_MARGIN_TOP = 30;//留给页眉的空间
        $PDF_MARGIN_RIGHT = 25;
        $pdf->SetMargins($PDF_MARGIN_LEFT, $PDF_MARGIN_TOP, $PDF_MARGIN_RIGHT);

        $file = "./upload/00.png";
        $x='';
        $y='';
        $w=190;
        $h=30;
        $type='';
        $link='';
        $align='';
        $resize=false;
        $dpi=300;
        $palign='';
        $ismask=false;
        $imgmask=false;
        $border=0;
        $fitbox=false;
        $hidden=false;
        $fitonpage=false;
        $alt=false;
        $altimgs=array();


        $pdf->Image($file, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border, $fitbox, $hidden, $fitonpage, $alt, $altimgs);

        $roomInfo = Db::table('ims_hc_meet_room')
            ->where(['room_id'=>$room_id])
            ->find();
        $number = $roomInfo["number"];
        $exhibitor_name = $roomInfo["exhibitor_name"];
        $builder_name = $roomInfo["builder_name"];


        $html = <<<EOD
        <h2 style="text-align: center">主场服务-付款通知单</h2>
<table border="1" style="text-align: center ">
<tr><td colspan="5" style="text-align: left">展位号以及展位名称：$number $exhibitor_name</td></tr>
<tr><td colspan="5" style="text-align: left">展位搭建商：$builder_name</td></tr>
<tr><th>序号</th><th>项目</th><th>数量</th><th>单价</th><th>总价</th></tr>
$html1
<tr><td colspan="4">合计：</td><td>$total</td></tr>
</table>
EOD;

        $pdf->SetFont('cid0cs', '', 14);
        $pdf->writeHTMLCell(0, 0, '', '50', $html, 0, 1, 0, true, '', true);

//        $pdf->writeHTML('<h2 style="color:red;text-align:center;">Hello World</h3>', true, false, true, false, '');
        $pdf->Output(date('YmdHis').'.pdf', 'D');
    }

}